package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.NumericalLimitsPoJo;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.OutstockDao;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductStockInfoEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.UpdateStockDataEntity;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseOutstockEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.business.WorkOrderOutstockEnum;
import com.xbongbong.saas.enums.product.AssembleProductEnum;
import com.xbongbong.saas.enums.product.ContractOutstockProductEnum;
import com.xbongbong.saas.enums.product.OutstockProductEnum;
import com.xbongbong.saas.help.BatchKeyHelp;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.OutstockSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getJsonObjectFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getLongFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getLongOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getStringOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 出库单model层接口实现类
 *
 * @author chaoxiong.lei
 * @Date 19:42 2019/1/29
 * @since v1.0
 **/
@Service("outstockModel")
public class OutstockModelImpl implements OutstockModel {
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private OutstockDao outstockDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private OutstockSubDataModel outstockSubDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CommonHelp commonHelp;

    @Override
    public List<String> getCorpidList() {
        return outstockDao.getCorpidList();
    }

    @Override
    public Integer insert(OutstockEntityExt entity) throws XbbException {
        // 先进行数据库的插入动作
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = outstockDao.insert(entity);
        // 插入ES
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_OUTSTOCK);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        return success;
    }

    /**
     * 查询单个实体
     *
     * @param key ID
     * @param corpid 公司
     * @return
     */
    @Override

    public OutstockEntityExt getByKey(Long key, String corpid) {
        OutstockEntityExt outstockEntityExt = outstockDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(outstockEntityExt), IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        return outstockEntityExt;
    }

    @Override
    public Integer update(OutstockEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        StandardizeDataUtil.standardizeNotString(entity);

        Integer success = outstockDao.update(entity);

        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            success = outstockDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新ES
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_OUTSTOCK);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }


        return success;
    }

    @Override
    public List<OutstockEntityExt> findEntitys(Map<String, Object> param) {
        List<OutstockEntityExt> entitys = outstockDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        }
        return entitys;
    }

    /**
     * 查询出库单Ids
     *
     * @param param 参数
     * @return List<Long> Id集合
     */
    @Override
    public List<Long> findIds(Map<String, Object> param) {
        return outstockDao.findIds(param);
    }

    @Override
    public Integer save(OutstockEntityExt entity) throws XbbException {
        Long id = entity.getId();
        if (id == null || Objects.equals(id, 0L)) {
            return insert(entity);
        }
        return update(entity);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return outstockDao.getEntitysCount(param);
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OUTSTOCK);
        paasEsModel.delete(deleteDTO);
        Integer integer = outstockDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB);
        return integer;
    }

    @Override
    public Integer updateBatchDataByType(List<UpdateStockDataEntity> updateList, String corpid) throws XbbException {
        Integer integer = outstockDao.updateBatchDataByType(updateList, corpid);
        paasEsModel.updateBatchDataByType(updateList, IndexTypeEnum.IDX_SAAS_OUTSTOCK);
        return integer;
    }

    @Override
    public Integer deleteBatch(List<Long> outstockIdIn, String corpid) throws XbbException {
        Integer integer = outstockDao.deleteBatch(outstockIdIn, corpid);
        paasEsModel.deleteBatch(outstockIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_OUTSTOCK);
        paasFormSubDataModel.deleteBatchByDataId(outstockIdIn, corpid, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteBatchImmediately(List<Long> outstockIdIn, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = outstockDao.deleteBatch(outstockIdIn, corpid);
        paasEsModel.deleteBatch(outstockIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_OUTSTOCK, refreshPolicy);

        paasFormSubDataModel.deleteBatchByDataId(outstockIdIn, corpid, IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer  = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = outstockDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_OUTSTOCK);
        }
        if (CollectionsUtil.isNotEmpty(subList)) {
            outstockSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer  = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = outstockDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OUTSTOCK, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            outstockSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    /**
     * 根据供应商ID查询采购退货出库单集合
     * @param param 参数
     * @return
     */
    @Override
    public List<OutstockEntityExt> getBySupplierId(Map<String, Object> param) {
        return outstockDao.getBySupplierId(param);
    }

    /**
     * 根据合同ID 获取合同下所有销售出库单
     * @param param 参数
     * @return
     */
    @Override
    public List<OutstockEntityExt> getByContractId(Map<String, Object> param) {
        return outstockDao.getByContractId(param);
    }



    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = outstockDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OUTSTOCK);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    @Override
    public List<OutstockEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return outstockDao.findEntitys(param);
    }

    @Override
    public List<OutstockEntityExt> getOutstockByTypeAndUpdateTime(Integer type, String corpid, Integer pageSize, Long idGte, Long startTime, Long endTime) {
        return outstockDao.getOutstockByTypeAndUpdateTime(type, corpid, pageSize, idGte, startTime, endTime);
    }

    @Override
    public Boolean formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        Integer businessType = formatExplainDTO.getBusinessType();
        boolean isWorkOrder = Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode());
        List<String> workOderAttrs = Arrays.asList(WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr(), WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr(), WorkOrderOutstockEnum.LINK_CONTACT.getAttr(), WorkOrderOutstockEnum.CUSTOMER_ADDRESS.getAttr());
        int index = 0;
        int selectProductIndex = -1;
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                selectProductIndex = index;
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                if (Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.INVENTORY.getCode())) {
                    explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.OUTSTOCK, corpid, BasicConstant.ZERO, false);
                }else {
                    explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.OUTSTOCK, corpid, BasicConstant.ONE, false);
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) && (Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.INVENTORY.getCode()))) {
                    List<? extends FieldAttrEntity> subFormArray = fieldAttrEntity.getSubForm().getItems();
                    Iterator<? extends FieldAttrEntity> iterator = subFormArray.iterator();
                    while (iterator.hasNext()) {
                        FieldAttrEntity subFormItem = iterator.next();
                        if (Objects.equals(subFormItem.getAttr(), SelectProductEnum.BATCH.getAttr())) {
                            subFormItem.setEditable(0);
                            break;
                        }
                    }
                }
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.MANAGER_ID.getAttr())) {
                if(fieldAttrEntity.getDefaultAttr() == null || (fieldAttrEntity.getDefaultAttr() != null &&  CollectionUtils.isEmpty(fieldAttrEntity.getDefaultAttr().getDefaultList()))) {
                    fieldAttrEntity.setDefaultAttr(defaultAttrHelp.setUserDefaultAttrPoJo(formatExplainDTO.getUserId(), formatExplainDTO.getLoginUser().getName(),formatExplainDTO.getLoginUser().getAvatar()));
                }
            } else if (isWorkOrder && workOderAttrs.contains(fieldAttrEntity.getAttr())) {
                fieldAttrEntity.setEditable(0);
                if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr())) {
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    for (FieldAttrEntity subAttrEntity : subExplainList) {
                        subAttrEntity.setEditable(0);
                    }
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
            }
            if (!Objects.equals(formatExplainDTO.getEditFormat(), true) && Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr())) {
                List<ItemPoJo> items = fieldAttrEntity.getItems();
                items.removeIf(item -> Objects.equals(item.getValue(), Objects.toString(OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode())));
            }
            // 销售出库单处理精度、数值范围
            if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                    && (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.PRODUCT_TOTAL.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.OTHER_EXPENSE.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.TOTAL_MONEY.getAttr()))) {
                if (selectProductIndex != -1) { // selectProductIndex未变动跳过
                    List<? extends FieldAttrEntity> subFormItems = explainList.get(selectProductIndex).getSubForm().getItems();
                    for (FieldAttrEntity subFormItem : subFormItems) {
                        if (Objects.equals(subFormItem.getAttr(), SelectProductEnum.PRICE.getAttr())) {
                            NumericalLimitsPoJo numericalLimits = new NumericalLimitsPoJo();
                            if (Objects.nonNull(subFormItem.getNumericalLimits())) {
                                numericalLimits.setMin(subFormItem.getNumericalLimits().getMin());
                                numericalLimits.setMax(subFormItem.getNumericalLimits().getMax());
                            }
                            fieldAttrEntity.setNumericalLimits(numericalLimits);
                            fieldAttrEntity.setNumericalLimitsFlag(subFormItem.getNumericalLimitsFlag());
                            fieldAttrEntity.setAccuracy(subFormItem.getAccuracy());
                            break;
                        }
                    }
                }
            }
            index++;
        }
        return !Objects.equals(formatExplainDTO.getBusinessType(),XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) || (Objects.nonNull(formatExplainDTO.getLinkBusinessType()));
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        formatExplainDTO.setEditFormat(true);
        String corpid = formatExplainDTO.getCorpid();
        formatAddExplain(formatExplainDTO);
        Integer type = formatExplainDTO.getResult().getInteger(OutstockEnum.TYPE.getAttr());
        // 编辑时产品仓库不可以修改，审批编辑除外（同新建）
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        JSONObject data = formatExplainDTO.getResult();
        data.put(OutstockEnum.TYPE.getAttr(),data.getString(OutstockEnum.TYPE.getAttr()));
        Integer outstockType = data.getInteger(OutstockEnum.TYPE.getAttr());
        Integer linkBusinessType = null;
        if (Objects.equals(outstockType, OutstockTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.CONTRACT_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.INVENTORY_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.TRANSFER_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.WORK_ORDER_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.WORK_ORDER_OUTSTOCK.getBusinessType();
        } else if (Objects.equals(outstockType, OutstockTypeEnum.MATERIEL_OUTSTOCK.getCode())) {
            linkBusinessType = OutstockTypeEnum.MATERIEL_OUTSTOCK.getBusinessType();
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                if (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy()) {
                    fieldAttrEntity.setEditable(0);
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())) {
                fieldAttrEntity.setEditable(0);
            }
            if (Objects.equals(attr, OutstockEnum.WAREHOUSE_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, OutstockEnum.TYPE.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, OutstockEnum.REF_ID.getAttr())) {
                fieldAttrEntity.setLinkedType(linkBusinessType);
            }else if (Objects.equals(attr, ContractOutstockEnum.LINK_CUSTOMER.getAttr()) && Objects.equals(type,OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())){
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, OutstockEnum.TIME.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, ContractOutstockEnum.OTHER_EXPENSE.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, ContractOutstockEnum.TOTAL_MONEY.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        // 格式化仓库字段
        showFormatHelp.formatLinkBusiness4Show(result, OutstockEnum.WAREHOUSE_ID.getAttr(), OutstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr(), OutstockEnum.WAREHOUSE_ID.getFieldType());

        // 格式化关联单据字段
        showFormatHelp.formatLinkBusiness4Show(result, OutstockEnum.REF_ID.getAttr(), OutstockEnum.REF_ID_LINKED_TEXT.getAttr(), OutstockEnum.REF_ID.getFieldType());
        OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(result.getInteger(OutstockEnum.TYPE.getAttr()));
        switch (outstockTypeEnum){
            case RETURNED_PURCHASE_OUTSTOCK:
                showFormatHelp.formatLinkBusiness4Show(result, ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getAttr(), ReturnedPurchaseOutstockEnum.LINK_SUPPLIER_HIDE.getAttr(), ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getFieldType());
                break;
            case CONTRACT_OUTSTOCK:
                showFormatHelp.formatLinkBusiness4Show(result, ContractOutstockEnum.LINK_CUSTOMER.getAttr(), ContractOutstockEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractOutstockEnum.LINK_CUSTOMER.getFieldType());
                break;
            case WORK_ORDER_OUTSTOCK:
                showFormatHelp.formatLinkBusiness4Show(result, WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr(), WorkOrderOutstockEnum.LINK_CUSTOMER_HIDE.getAttr(), WorkOrderOutstockEnum.LINK_CUSTOMER.getFieldType());
                showFormatHelp.formatLinkBusiness4Show(result, WorkOrderOutstockEnum.LINK_CONTACT.getAttr(), WorkOrderOutstockEnum.LINK_CONTACT_HIDE.getAttr(), WorkOrderOutstockEnum.LINK_CONTACT.getFieldType());
                break;
        }
        if (Objects.equals(result.getInteger(OutstockEnum.TYPE.getAttr()),OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())){
            showFormatHelp.formatLinkBusiness4Show(result, ContractOutstockEnum.LINK_CUSTOMER.getAttr(), ContractOutstockEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractOutstockEnum.LINK_CUSTOMER.getFieldType());
        }
    }

    @Override
    public void getProductList(String corpid, List<OutstockProductEntity> outstockProductList, List<ProductStockInfoEntity> productStockInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 获取前端返回的产品成本
            Double cost = getDoubleOrDefaultFromFormData(productArrayJSONObject, StringConstant.PRODUCT_COST, 0D);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 折扣
            Double discount = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.SALE_DISCOUNT.getSaasAttr(), 0D);
            // 出库仓库
            JSONObject warehouse = getJsonObjectFromFormData(productArrayJSONObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            // 出库仓库
            Double price = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.SALE_PRODUCT_PRICE.getSaasAttr(), 0D);
            Long warehouseId = 0L;
            if (warehouse != null && warehouse.size() > 0) {
                warehouseId = getLongOrDefaultFromFormData(warehouse, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            }
            // 批次
            String batch = getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.BATCH.getSaasAttr(), "");
            // 生产日期
            Long date = DateTimeUtil.getInt(getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCE_DATE.getSaasAttr(), ""), DateUtil.SDFDate);
            // 保质期 存的是天数
            Long guaranteePeriod = getLongFromFormData(productArrayJSONObject, RelativeProductEnum.GUARANTEE_PERIOD.getSaasAttr());
            // 产品备注
            String memo = getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                OutstockProductEntity productEntity = new OutstockProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductPrice(price);
                productEntity.setProductNo(productNo);
                productEntity.setProductUnit(unit);
                productEntity.setDiscount(discount);
                productEntity.setProductSpecification(specification);
                productEntity.setCost(cost);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setSort(sort);
                productEntity.setBatch(batch);
                //JSONObject jsonObject = new JSONObject();
                if (guaranteePeriod != null) {
                    productEntity.setGuaranteePeriod(guaranteePeriod);
                    //jsonObject.put(OutstockProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriod * 86400);
                }
                productEntity.setProduceDate(date);
                productEntity.setMemo(memo);

                outstockProductList.add(productEntity);
            }
        }
    }

    @Override
    public void formatNewProductList(String corpid, List<OutstockProductEntity> outstockProductEntityList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            sort++;
            JSONObject pageProductObject = productArray.getJSONObject(i);
            Long pageProductId = pageProductObject.getLong(OutstockProductEnum.PRODUCT.getAttr());
            Double productNum = getDoubleOrDefaultFromFormData(pageProductObject, OutstockProductEnum.NUM.getAttr(), 0D);
            String memo = getStringOrDefaultFromFormData(pageProductObject, OutstockProductEnum.MEMO.getAttr(), "");
            String batch = getStringOrDefaultFromFormData(pageProductObject, OutstockProductEnum.BATCH.getAttr(), "");
            Long date = getLongOrDefaultFromFormData(pageProductObject, OutstockProductEnum.PRODUCE_DATE.getAttr(), 0L);
            Long guaranteePeriod = getLongOrDefaultFromFormData(pageProductObject, OutstockProductEnum.GUARANTEE_PERIOD.getAttr(), 0L);
            Double cost = getDoubleOrDefaultFromFormData(pageProductObject, OutstockProductEnum.COST.getAttr(), 0D);
            SaveFormatHelp.formatLinkBusiness4Save(pageProductObject,OutstockProductEnum.WAREHOUSE.getAttr(), "warehouseName", FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            Long warehouseId = pageProductObject.getLong(OutstockProductEnum.WAREHOUSE.getAttr());
            Long subProductId = getLongFromFormData(pageProductObject, BusinessConstant.PRODUCT_SUB_ID);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                OutstockProductEntity productEntity = new OutstockProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setProductPrice(price);
                productEntity.setCost(cost);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                productEntity.setBatch(batch);
                if (Objects.nonNull(subProductId)) {
                    productEntity.setId(subProductId);
                }
                if (guaranteePeriod != null) {
                    productEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                }
                productEntity.setProduceDate(date);
                productEntity.setMemo(memo);
                productEntity.setData(pageProductObject);
                outstockProductEntityList.add(productEntity);
            }
        }
    }

    @Override
    public void formatProduct4Show3(Map<String, Double> productBatchWarehouseMap, Map<String, Double> productWarehouseMap, Map<Long, String> warehouseNameMap, List<OutstockProductEntity> outstockProductEntityList, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum, Integer type, Map<Long, List<MultiUnitPricePoJo>> priceMap) throws XbbException {
        JSONArray productArray = new JSONArray();
        for (OutstockProductEntity outstockProductEntity : outstockProductEntityList){
            JSONObject json;
            if (Objects.equals(type,OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())){
                if (Objects.nonNull(priceMap) && Objects.nonNull(priceMap.get(outstockProductEntity.getProductId()))) {
                    outstockProductEntity.setProductPriceArr(JSONArray.parseArray(JSONArray.toJSONString(priceMap.get(outstockProductEntity.getProductId()))));
                }
                json = formatSingleContractOutstockProduct(outstockProductEntity);
            }else {
                json = formatSingleProduct(outstockProductEntity);
            }
            if (Objects.equals(type, OutstockTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode()) || Objects.equals(type,OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
                json.put(SelectProductEnum.SOURCE_PRICE.getAttr(),json.getDouble(SelectProductEnum.COST.getAttr()));
            }
            String key;
            if (StringUtil.isEmpty(outstockProductEntity.getBatch())) {
                key = outstockProductEntity.getProductId() + "_" + outstockProductEntity.getWarehouseId();
            } else {
                key = BatchKeyHelp.getBatchKey(outstockProductEntity.getProductId(), outstockProductEntity.getWarehouseId(), outstockProductEntity.getBatch(), outstockProductEntity.getProduceDate(), outstockProductEntity.getGuaranteePeriod());
            }

            if (StringUtil.isEmpty(outstockProductEntity.getBatch())) {
                json.put(OutstockProductEnum.STOCK.getAttr(), productWarehouseMap.get(key));
            } else {
                json.put(OutstockProductEnum.STOCK.getAttr(), productBatchWarehouseMap.get(key));
            }

            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,outstockProductEntity.getId());
                if (Objects.isNull(outstockProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            } else if (updateDataTypeEnum.isLinkAdd()) {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                json.put(BusinessConstant.REF_PRODUCT_ID, outstockProductEntity.getId());
            } else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(outstockProductEntity.getCorpid(),outstockProductEntity.getProductUnit()));
            }
            JSONObject batchObj = new JSONObject();
            batchObj.put("text",json.getString(OutstockProductEnum.BATCH.getAttr()));
            batchObj.put("value",json.getString(OutstockProductEnum.BATCH.getAttr()));
            json.put(AssembleProductEnum.BATCH.getAttr(),batchObj);
            JSONObject warehouseObj = new JSONObject();
            warehouseObj.put("id",outstockProductEntity.getWarehouseId());
            warehouseObj.put("name",warehouseNameMap.getOrDefault(outstockProductEntity.getWarehouseId(),""));
            json.put(AssembleProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
            json.put("refId",outstockProductEntity.getId());
            productArray.add(json);
        }
        data.put(OutstockEnum.PRODUCT.getAttr(),productArray);
    }

    @Override
    public JSONObject formatSingleProduct(OutstockProductEntity outstockProductEntity) {
        JSONObject json = outstockProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, outstockProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (OutstockProductEnum outstockProductEnum :OutstockProductEnum.values()){
                String attr = outstockProductEnum.getAttr();
                switch (outstockProductEnum){
                    case PRODUCT:
                        json.put(attr,outstockProductEntity.getProductId());
                        break;
                    case WAREHOUSE:
                        json.put(attr,outstockProductEntity.getWarehouseId());
                        break;
                    case NUM:
                        json.put(attr,outstockProductEntity.getProductNum());
                        break;
                    case COST:
                        json.put(attr,outstockProductEntity.getCost());
                        break;
                    case TOTAL_COST:
                        Double cost = Objects.isNull(outstockProductEntity.getCost()) ? 0D: outstockProductEntity.getCost();
                        Double productNum = Objects.isNull(outstockProductEntity.getProductNum()) ? 0D: outstockProductEntity.getProductNum();
                        json.put(attr, Arith.mul(cost,productNum));
                        break;
                    case MEMO:
                        json.put(attr,outstockProductEntity.getMemo());
                        break;
                    case BATCH:
                        json.put(attr,outstockProductEntity.getBatch());
                        break;
                    case PRODUCE_DATE:
                        json.put(attr,outstockProductEntity.getProduceDate());
                        break;
                    case GUARANTEE_PERIOD:
                        if (Objects.nonNull(outstockProductEntity.getGuaranteePeriod()) && !Objects.equals(outstockProductEntity.getProduceDate(), 0L)) {
                            json.put(attr, Arith.div(outstockProductEntity.getGuaranteePeriod(), TimeConstant.SECONDS_PER_DAY));
                        }
                        break;
                    case EXPIRE_DATE:
                        if (Objects.nonNull(outstockProductEntity.getGuaranteePeriod()) && Objects.nonNull(outstockProductEntity.getProduceDate())) {
                            json.put(attr, Arith.add(outstockProductEntity.getProduceDate(), outstockProductEntity.getGuaranteePeriod()));
                        }
                        break;
                    case UNIT:
                        json.put(attr, outstockProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        } else if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
            if (Objects.equals(outstockProductEntity.getProduceDate(), 0L) || Objects.isNull(outstockProductEntity.getProduceDate())) {
                json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            }
        }
        return json;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, Boolean forProcess, Integer operate, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        Integer type = data.getInteger(OutstockEnum.TYPE.getAttr());
        // 获取关联产品
        List<OutstockProductEntity> outstockProductEntityList = new ArrayList<>();
        List<ProductStockInfoEntity> productStockInfoList = new ArrayList<>();
        Map<Long, JSONArray> refProductSeqMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdList = new HashSet<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(OutstockEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, OutstockEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArr);
                getProductList(corpid, outstockProductEntityList, productStockInfoList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(OutstockEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(OutstockProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, outstockProductEntityList, jsonArray, productMap);
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            outstockProductEntityList = outstockProductModel.getProductsByOutstockIdIn( corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
            if (commonHelp.isOpenWorkFlow(corpid) && Objects.nonNull(forProcess) && forProcess && Objects.equals(WorkflowOperateEnum.ADD.getType(), operate)) {
                // 工作流的详情，需要从上下文中拼接序列号数据
                JSONArray productArray = data.getJSONArray(OutstockEnum.PRODUCT.getAttr());
                for (int i = 0; i < productArray.size(); i++) {
                    JSONObject jsonObject = productArray.getJSONObject(i);
                    refProductSeqMap.put(jsonObject.getLong(BusinessConstant.PRODUCT_SUB_ID), jsonObject.getJSONArray(ProductConstant.SEQ));
                }
            } else {
                List<ProductSerialFlowEntity> productSerialFlowList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), OutstockTypeEnum.getStockBusinessTypeByCode(type), corpid);
                for (ProductSerialFlowEntity entity : productSerialFlowList) {
                    JSONArray serialArray = refProductSeqMap.getOrDefault(entity.getRefProductId(), new JSONArray());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(SerialEnum.SERIAL.getAttr(), entity.getSeq());
                    jsonObject.put(SerialEnum.MEMO.getAttr(), entity.getMemo());
                    serialArray.add(jsonObject);

                    refProductSeqMap.put(entity.getRefProductId(), serialArray);
                }
            }

            outstockProductEntityList.forEach(item -> {
                productIdList.add(item.getProductId());
                JSONArray seqArray = refProductSeqMap.getOrDefault(item.getId(), null);
                if (Objects.nonNull(seqArray)) {
                    item.getData().put(ProductConstant.SEQ, seqArray);
                }
            });
        }
        Map<Long, List<MultiUnitPricePoJo>> priceMap = null;
        if (Objects.equals(type,OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
            Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIds(corpid, new ArrayList<>(productIdList), DelEnum.NORMAL.getDel(), Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID, ProductEnum.getAttrConnectData(ProductEnum.STOCK), ProductEnum.getEsAttr4Keyword(ProductEnum.NAME), ProductEnum.getAttrConnectData(ProductEnum.ONLINE), ProductEnum.getAttrConnectData(ProductEnum.ENABLE_MULTI_UNIT)));
            Set<Long> multiUnitProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            productMap.forEach((key,value)->{
                if (Objects.equals(value.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                    multiUnitProductIds.add(key);
                }
            });
            priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIds);
        }
        Set<Long> warehouseIdList = new HashSet<>();
        Set<String> batchKeyList = new HashSet<>();
        Set<String> warehouseKeySet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        outstockProductEntityList.forEach(item -> {
            warehouseKeySet.add(item.getProductId() + "_" + item.getWarehouseId());
            warehouseIdList.add(item.getWarehouseId());
            if (StringUtil.isNotEmpty(item.getBatch())) {
                String key = BatchKeyHelp.getBatchKey(item.getProductId(), item.getWarehouseId(), item.getBatch(), item.getProduceDate(), item.getGuaranteePeriod());
                batchKeyList.add(key);
            }
        });
        // 批次库存
        Map<String, Double> productBatchWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!batchKeyList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("batchKeyIn", batchKeyList);
            List<ProductStockEntity> productStockEntities = productStockModel.findEntitys(params);
            productStockEntities.forEach(item -> {
                productBatchWarehouseMap.put(item.getBatchKey(), item.getNum());
            });
        }
        // 分仓库存
        Map<String, Double> productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!warehouseKeySet.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("warehouseKeyIn",warehouseKeySet);
            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitysWithWarehouseChecked(params,null);
            productWarehouseEntities.forEach(item -> {
                String key = item.getProductId() + "_" + item.getWarehouseId();
                productWarehouseMap.put(key, item.getNum());
                warehouseNameMap.put(item.getWarehouseId(),item.getWarehouseName());
            });
        }
        formatProduct4Show3(productBatchWarehouseMap, productWarehouseMap,warehouseNameMap, outstockProductEntityList, data, updateDataTypeEnum,type, priceMap);
    }

    @Override
    public JSONObject formatSingleContractOutstockProduct(OutstockProductEntity outstockProductEntity) {
        JSONObject json = outstockProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, outstockProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (ContractOutstockProductEnum outstockProductEnum :ContractOutstockProductEnum.values()){
                String attr = outstockProductEnum.getAttr();
                switch (outstockProductEnum){
                    case PRODUCT:
                        json.put(attr,outstockProductEntity.getProductId());
                        break;
                    case WAREHOUSE:
                        json.put(attr,outstockProductEntity.getWarehouseId());
                        break;
                    case NUM:
                        json.put(attr,outstockProductEntity.getProductNum());
                        break;
                    case COST:
                        json.put(attr,outstockProductEntity.getCost());
                        break;
                    case TOTAL_COST:
                        Double cost = Objects.isNull(outstockProductEntity.getCost()) ? 0D: outstockProductEntity.getCost();
                        Double productNum = Objects.isNull(outstockProductEntity.getProductNum()) ? 0D: outstockProductEntity.getProductNum();
                        json.put(attr,Arith.mul(cost,productNum));
                        break;
                    case MEMO:
                        json.put(attr,outstockProductEntity.getMemo());
                        break;
                    case BATCH:
                        json.put(attr,outstockProductEntity.getBatch());
                        break;
                    case PRODUCE_DATE:
                        json.put(attr,outstockProductEntity.getProduceDate());
                        break;
                    case GUARANTEE_PERIOD:
                        if (Objects.nonNull(outstockProductEntity.getGuaranteePeriod())) {
                            json.put(attr, Arith.div(outstockProductEntity.getGuaranteePeriod(), TimeConstant.SECONDS_PER_DAY));
                        }
                        break;
                    case EXPIRE_DATE:
                        if (Objects.nonNull(outstockProductEntity.getGuaranteePeriod()) && Objects.nonNull(outstockProductEntity.getProduceDate())) {
                            json.put(attr, Arith.add(outstockProductEntity.getProduceDate(), outstockProductEntity.getGuaranteePeriod()));
                        }
                        break;
                    case UNIT:
                        json.put(attr, outstockProductEntity.getProductUnit());
                        break;
                    case PRICE:
                        json.put(attr, 0D);
                        break;
                    case SELLING_PRICE:
                        json.put(attr, outstockProductEntity.getProductPrice());
                        break;
                    case DISCOUNT:
                        json.put(attr, outstockProductEntity.getDiscount());
                        break;
                    case SUBTOTAL:
                        if (Objects.nonNull(outstockProductEntity.getProductPrice()) && Objects.nonNull(outstockProductEntity.getProductNum())) {
                            json.put(attr, Arith.mul(outstockProductEntity.getProductPrice(), outstockProductEntity.getProductNum()));
                        }
                        break;
                    default:
                        break;
                }
            }
        } else if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
            if (Objects.equals(outstockProductEntity.getProduceDate(), 0L) || Objects.isNull(outstockProductEntity.getProduceDate())) {
                json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            }
        }
        if (Objects.nonNull(outstockProductEntity.getProductPriceArr())) {
            json.put(ProductConstant.PRODUCT_PRICE, outstockProductEntity.getProductPriceArr());
        }
        return json;
    }

    @Override
    public void formatDataForDistributor(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        // 格式化仓库字段
        showFormatHelp.formatLinkBusiness4Show(result, OutstockEnum.WAREHOUSE_ID.getAttr(), OutstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr(), OutstockEnum.WAREHOUSE_ID.getFieldType());
        // 格式化关联单据字段
        showFormatHelp.formatLinkBusiness4Show(result, OutstockEnum.REF_ID.getAttr(), OutstockEnum.REF_ID_LINKED_TEXT.getAttr(), OutstockEnum.REF_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, OrderOutStockEnum.LINK_DISTRIBUTOR.getAttr(), OrderOutStockEnum.LINK_DISTRIBUTOR_HIDE.getAttr(), OrderOutStockEnum.LINK_DISTRIBUTOR.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, OrderOutStockEnum.LINK_PARTNER_RECEIVER.getAttr(), OrderOutStockEnum.LINK_PARTNER_RECEIVER_HIDE.getAttr(), OrderOutStockEnum.LINK_PARTNER_RECEIVER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, OrderOutStockEnum.SEND_NAME.getAttr(), OrderOutStockEnum.LINK_SEND_HIDE.getAttr(), OrderOutStockEnum.LINK_SEND_HIDE.getFieldType());
    }

    @Override
    public List<PaasFormDataEntityExt> findOutstockList(String corpid, Integer type, Long refId, List<Integer> flowStatusIn, List<String> fieldList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        boolQueryBuilder.filter(termQuery(esData + OutstockEnum.REF_ID.getAttr(), refId));
        boolQueryBuilder.filter(termQuery(esData + OutstockEnum.TYPE.getAttr(), type));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), flowStatusIn));
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        return esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
    }

    @Override
    public Map<String, BigDecimal> sumJsonByIdAndAttr(String corpid, List<Long> idList, List<String> attrList) {
        if (StringUtil.isEmpty(corpid) || CollectionUtils.isEmpty(idList) || CollectionUtils.isEmpty(attrList)) {
            return new HashMap<>(0);
        }
        return outstockDao.sumJsonByIdAndAttr(corpid, idList, attrList);
    }

    @Override
    public List<OutstockEntityExt> listInId(String corpid, List<Long> idList) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("del", 0);
        param.put("corpid", corpid);
        param.put("idIn", idList);
        return outstockDao.findEntitys(param);
    }

    @Override
    public List<PaasFormDataEntityExt> findOutstockList(List<Long> refIdIn, Integer type, List<Integer> flowStatusIn, String corpid, List<String> fieldList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (Objects.isNull(refIdIn) || refIdIn.isEmpty()) {
            return new ArrayList<>();
        }
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        if (Objects.nonNull(refIdIn) && !refIdIn.isEmpty()) {
            boolQueryBuilder.filter(termsQuery(esData + OutstockEnum.REF_ID.getAttr(), refIdIn));
        }
        if (Objects.nonNull(type)) {
            boolQueryBuilder.filter(termQuery(esData + OutstockEnum.TYPE.getAttr(), type));
        }
        if (Objects.nonNull(flowStatusIn) && !flowStatusIn.isEmpty()) {
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), flowStatusIn));
        }
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        List<PaasFormDataEntityExt> outstockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        return outstockList;
    }

    @Override
    public List<Long> hasDownstreamList(String corpid, List<Long> idIn, int type) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.REF_ID),idIn));
        boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE), type));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field(OutstockEnum.getEsAttr4Keyword(OutstockEnum.REF_ID));
        //该桶要置为最大
        termsAggregationBuilder.size(SizeConstant.TERM_AGG_MAX_BUCKETS);
        termsAggregationBuilder.executionHint(ElasticConstant.EXECUTION_HINT);
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, termsAggregationBuilder);
        List<Long> list = new ArrayList<>();
        for (Object buckets : resultJsonObject.getJSONArray("buckets")) {
            JSONObject dataJsonObject = (JSONObject) buckets;
            Long id = dataJsonObject.getLong("key");
            if (dataJsonObject.getInteger("doc_count") > 0){
                list.add(id);
            }
        }
        return list;
    }
}
